<template>
  <Form ref="validForm" :model="drawer" :rules="ruleValidate">
    <FormItem label="职务名" label-position="top" prop="name">
      <Input v-model="drawer.name" placeholder="请输入职务名称"/>
    </FormItem>

    <FormItem label="职务描述" label-position="top">
      <Input type="textarea" v-model="drawer.description" :rows="4" placeholder="请输入职务描述信息"/>
    </FormItem>

    <FormItem label="状态" label-position="top" prop="state">
      <Switch size="large" v-model="drawer.state">
        <template #open>
          <span>启用</span>
        </template>
        <template #close>
          <span>禁用</span>
        </template>
      </Switch>
    </FormItem>
  </Form>

  <div class="demo-drawer-footer">
    <Button style="margin-right: 8px" @click="$emit('close-win', false)">关闭</Button>
    <Button type="primary" @click="handleForm">保存</Button>
  </div>
</template>

<script>
export default {
  props: {
    drawer: {type: Object, required: true},
  },
  data() {
    return {
      error: {},
      ruleValidate: {
        name: [
          {required: true, message: "职务名不允许为空", trigger: 'blur'},
          {type: "string", max:100, message: "职务名过长", trigger: 'blur'},
        ],
        state: [
          {type: "boolean", message: "状态必须是一个boolean类型的值", trigger: "blur"}
        ]
      }
    }
  },
  emits: ["close-win"],
  methods: {
    handleForm() {
      this.error = {} ;
      // 校验表单参数
      this.$refs.validForm.validate(valid => {
        if (valid) {
          if (this.drawer.id == null) {
            // 保存方法
            this.handleSave();
          }else{
            //更新方法
            this.handleUpdate();
          }
        }
      })
    },
    handleSave() {
      this.$api.savePosition(this.drawer).then(ret=> {
         if (ret.data.status) {
           this.$tips.success("保存职务");
           this.$emit("close-win", "save");
         }else{
           this.error = ret.data.error ;
         }
      })

    },
    handleUpdate() {
      this.$api.updatePosition(this.drawer).then(ret=> {
        if (ret.data.status) {
          this.$tips.success("修改职务");
          this.$emit("close-win", "update");
        }else{
          this.error = ret.data.error ;
        }
      })
    },
    resetValidForm() {
      this.$refs.validForm.resetFields();
      this.error = {} ;
    },
  },
}
</script>

<style scoped>
.demo-drawer-footer {
  width: 100%;
  position: absolute;
  bottom: 0;
  left: 0;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: right;
  background: #fff;
}
</style>